package juc.jmm;
/*
* 犹豫模式
* */
public class Test3 {
    public static void main(String[] args) throws InterruptedException {
        Balking balking = new Balking();
        balking.start();
        balking.start();
        balking.start();
        Thread.sleep(3000);
        balking.stop();
    }
}
class Balking{
     private volatile boolean stop;
     private Thread monitor;
     private volatile boolean isExcutor;
     //启动监控线程... 只需要一个线程监控  这时候就要保证这个方法只被执行一次
     public void start(){//
         synchronized (this){
             if(isExcutor)return;
             isExcutor=true;
         }
         monitor = new Thread(() -> {
            while (true){
                if(stop){
                    System.out.println("料理后事...");
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            isExcutor=false;
         });
         monitor.start();
     }
     public void stop(){
         stop=true;
         monitor.interrupt();
     }
}
